import config from '@/config'
import errorCode from '@/util/errorCode'

let timeout = 10000
const baseUrl = config.baseUrl

/**
 * 请求拦截
 * @param {*} config 
 * @returns 
 */
const request = config => {
  // 确保 config.header 是一个对象
  config.header = config.header || {}
  const key = getRequestKey()
  // console.log('key ----------', key)

  // 获取请求key 获取接口请求权限
  config.header['Request-Key'] = key + ''

  return new Promise((resolve, reject) => {
    uni.request({
      method: config.method || 'get',
      timeout: config.timeout || timeout,
      url: config.baseUrl || baseUrl + config.url,
      data: config.data,
      header: config.header,
      dataType: 'json',
      success: (response) => {
        let res = response
        const code = res.data.code || 200
        const msg = res.data.message
        if (code === 200) {
          resolve(res.data)
        } else {
          reject({ code, msg })
        }
      },
      fail: (error) => {
        // 处理请求失败的情况，例如超时、网络错误等
        reject(errorCode.handleRequestError(error))
      }
    })
  })
}

/**
 * 获取请求动态令牌 获取访问权限
 * @returns 请求动态令牌
 */
function getRequestKey() {
  const now = new Date()
  return Math.floor(now.getTime() / 1000)
}

export default request